/* config-overrides.js */
/*
* @Author: mzhang.eric
* @Last Modified time: 2019-01-10 18:37:17
* @Description: 使用 react-app-rewired 扩展和改造 CRA v2.1.1 项目, 基于 webpack v4.19.1  + react-app-rewired v1.6.2 版本
*/
const {
    override,
    fixBabelImports,
    addLessLoader,
    addDecoratorsLegacy,
    disableEsLint,
    addBundleVisualizer,
    addWebpackPlugin,
    addWebpackAlias,
    adjustWorkbox,
    overrideDevServer,
    watchAll
} = require("customize-cra");
const path = require("path");

const glob = require("glob")
const fs=require('fs')
module.exports = {
    webpack: override(
        // enable legacy decorators babel plugin
        addDecoratorsLegacy(),

        // disable eslint in webpack
        disableEsLint(),

        // add webpack bundle visualizer if BUNDLE_VISUALIZE flag is enabled
        process.env.BUNDLE_VISUALIZE == 1 && addBundleVisualizer(),

        // add an alias for "ag-grid-react" imports
        addWebpackAlias({
            ["ag-grid-react$"]: path.resolve(__dirname, "src/shared/agGridWrapper.js")
        }),

        // adjust the underlying workbox
        adjustWorkbox(wb =>
            Object.assign(wb, {
                skipWaiting: true,
                exclude: (wb.exclude || []).concat("index.html")
            })
        ),
        fixBabelImports('import',{
            libraryName:'antd',
            libraryDirectory:'es',
            style:true
        }),
        addLessLoader({
            javascriptEnabled:true,
            modifyVars:{'@primary-color':'#1DA57A'}
        }),
        addWebpackPlugin(function (compiler) {

            compiler.hooks.thisCompilation.tap('compilation',(compilation,params)=>{

                return;
                compilation.hooks.addEntry.tap('addEntry',(entry, name)=>{

                    let imports=[];
                    let routes=[];
                    let rs = glob.sync("./src/pages/**/*.js");
                    rs.forEach(function(file,index){
                        let code= fs.readFileSync(file,"utf8");
                        if(code){

                            let match,re = /export\s+(default\s+)?(class|function)\s+(?<component>[A-Z][0-9a-zA-Z_]+)/g;
                            /*
                            while( match = re.exec(code)){
                                console.log(match[1]);
                            }*/
                            let find=code.matchAll(re)
                            let components=[];
                            let defaultComponent=null;
                            for(match of find){
                                if(match.indexOf('default')>-1){
                                    defaultComponent=match.groups['component']
                                }
                                components.push(match.groups['component'])
                            }
                            if(components.length==1){
                                routes.push({
                                    path:"/"+components[0].toLowerCase(),
                                    component:components[0],
                                    exact:true
                                })
                                imports.push(`import ${components[0]} from '../src/pages/${components[0].toLowerCase()}' `)
                            }else if(components.length>1){
                                let subRoutes=[];
                                routes.push({
                                    path:"/"+defaultComponent.toLowerCase(),
                                    component:defaultComponent,
                                    exact:true,
                                    routes:subRoutes
                                })
                                components.forEach(component=>{
                                    if(component!==defaultComponent){
                                        subRoutes.push({
                                            path:"/"+component.toLowerCase(),
                                            component:component,
                                            exact:true,
                                        })
                                    }
                                })

                                let index=components.indexOf(defaultComponent);
                                if(index>-1){
                                    components.splice(index,1);
                                }
                                imports.push(`import ${defaultComponent},{${components.toString()}} from './src/pages/${defaultComponent.toLowerCase()}' `)
                            }
                        }
                    });

                    if(routes.length>0){
                        let lines='';
                        imports.forEach(data=>{
                            lines+=data+"\r\n"
                        })
                        let indent='         '
                        lines+='const  routes = [\r\n'

                        for (let i = 0; i < routes.length; i++) {

                            if(i<routes.length-1){
                                lines+=JSON.stringify(routes[i],null, "\t")+',\r\n'
                            }else{
                                lines+=JSON.stringify(routes[i], null, "\t")+'\r\n'
                            }

                        }

                        lines+=']\r\n'
                        lines+='export default routes;'

                        rs = glob.sync("./src/router/index.js");
                        rs.forEach(function(file,index){

                            let fd=fs.openSync(file,"w+")

                            fs.writeSync(fd,lines,0,'utf8');

                            fs.closeSync(fd)

                        })
                    }

                });



            })

        } )
    ),
    devServer: overrideDevServer(
        // dev server plugin
       // watchAll()
    )
};
